import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

//对应Servlet/Servlet的基本使用/HttpServletRequest类
//示例1: 打印请求信息
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //把生成的响应的body给放到respBody中
        StringBuilder respBody = new StringBuilder();
        respBody.append(req.getProtocol());//返回请求协议的名称和版本。
        respBody.append("<br>");
        respBody.append(req.getMethod());//返回一个方法
        respBody.append("<br>");
        respBody.append(req.getRequestURI());//从协议名称直到HTTP请求的第一行的查询字符串中，返回该请求的URL的一部分。
        respBody.append("<br>");
        respBody.append(req.getContextPath());//返回指示请求上下文的请求URI部分。
        respBody.append("<br>");
        respBody.append(req.getQueryString());//得到完整的query string 例如:a=10&b=20,没有则为null
        //发送请求的时候可以构造query string
        respBody.append("<br>");

        respBody.append("<h3>headers.</h3>");
        Enumeration<String> headerNames = req.getHeaderNames();//返回一个String对象的枚举，包含在该请求中包含的参数的名称。
        while(headerNames.hasMoreElements()){
            String headerName = headerNames.nextElement();
            respBody.append(headerName+":");
            respBody.append(req.getHeader(headerName));
            respBody.append("<br></br>");//这里是两个换行符...
        }

        resp.getWriter().write(respBody.toString());//把构造的字符串写到响应里去
        //然后由Tomcat把字符串结构的请求解析成一个结构化的数据=>从字符串到结构化数据的过程,称为"反序列化"
    }
}

// 通过URL发送一个get请求,得到的页面是:
//HTTP/1.1
//GET
///Java_servlet/showRequest
///Java_servlet
//a=10&b=20
//headers.
//host:127.0.0.1:8080
//
//connection:keep-alive
//
//cache-control:max-age=0
//
//sec-ch-ua:" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
//
//sec-ch-ua-mobile:?0
//
//sec-ch-ua-platform:"Windows"
//
//upgrade-insecure-requests:1
//
//user-agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
//
//accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
//
//sec-fetch-site:none
//
//sec-fetch-mode:navigate
//
//sec-fetch-user:?1
//
//sec-fetch-dest:document
//
//accept-encoding:gzip, deflate, br
//
//accept-language:zh-CN,zh;q=0.9


